//引入数据库原型操作数据库
const User = require('../model/user_model')

class UserService {
    //创建用户
    async createUser(user_name, password) {
        // console.log(aaa);
        //await 返回Promise的值和对象
        const res = await User.create({
            //表的字段
            user_name, password
        })
        console.log(res);

        return res
    }

    //查询用户 
    async getUserInfo({ id, user_name, password, IsAdmin }) {
        const whereOpt = {}

        id && Object.assign(whereOpt, { id })
        user_name && Object.assign(whereOpt, { user_name })
        password && Object.assign(whereOpt, { password })
        IsAdmin && Object.assign(whereOpt, { IsAdmin })

        const res = await User.findOne({
            attributes: ['id', 'user_name', 'password', 'IsAdmin'],
            where: whereOpt,
        })

        return res ? res.dataValues : null
    }

    //更新用户信息 
    async UpdateUserinfo({ id, user_name, password, IsAdmin }) {
        const whereOpt = { id }
        // console.log(password);

        const newUser = {}
        user_name && Object.assign(newUser, { user_name })
        password && Object.assign(newUser, { password })
        IsAdmin && Object.assign(newUser, { IsAdmin })
        const res = await User.update(newUser, { where: whereOpt });
        return res[0] > 0 ? true : false

    } catch(error) {
        console.log(error);
    }
    

}

module.exports = new UserService()